////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.monitor;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DateUtils;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.MonitorGroup;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.adapter.UserDiaryHolder;
import cc.telecomdigital.tdstock.adapter.UserDiaryItemAdapter;

/**
 * 
 * @author haibo
 * 
 *  for monitor item   -- stock diary
 *
 */
public class StockDiaryActivity extends BaseActivity
{
	protected static final String	TAG	= StockDiaryActivity.class
										.getSimpleName();
	//private  static final long START_ID = 90000l; 

	private ListView			_listView;
	private Button				_toolBtnReturn;
	private TextView			_top_bar_title;
	private ViewGroup			_diary_add;
	private DBHelper			_dbHelper;

	private String				_itemCode;					;
	private String				_itemCurrentPrice;
	
	private UserDiaryItemAdapter	_newAdapter;
	private List<UserDiaryHolder>	_list;

	
	//为UserDiaryItemAdapter提供访问接口
	public List<UserDiaryHolder> get_list() {
		return _list;
	}
	//为UserDiaryItemAdapter提供访问接口
	public DBHelper get_dbHelper() {
		return _dbHelper;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.stock_diary);
		resetMinHeightOnWorkCenter();
		if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}
		_top_bar_title = (TextView) findViewById(R.id.top_bar_title);
		_diary_add = (ViewGroup) findViewById(R.id.diary_add);
		_diary_add.setFocusable(true);
		_diary_add.setClickable(true);
		_diary_add.setOnClickListener(new NewDiary(this));

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				// BMP Mode by ouyangzhihui 2011-10-13
				Class<? extends Activity> _cls = PortfolioActivity.class;
				if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
				{
					_cls = BMPPortfolioActivity.class;
				}
				
				Intent intent = new Intent(getApplicationContext(), _cls);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(_cls, intent);
			}
		});

		_listView = (ListView) findViewById(R.id.diary_history);
		_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				// TODO Auto-generated method stub
				_newAdapter.new EdtDiary(StockDiaryActivity.this, pos).onClick(arg1);
			}
		});
		_list = new ArrayList<UserDiaryHolder>();
		
		setAdapterToAddAnotherClickableBtn();
	}

	@Override
	protected void onPause(){
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume(){
		// TODO Auto-generated method stub
		if (_dbHelper == null){
			_dbHelper = new DBHelper(this);
		}
		super.onResume();
		updateLocalData();
		updateAdapter();
		//if(_newAdapter.isEmpty()){
			//resetAdapterToAddAnotherClickableBtn();
		//}
		_listView.invalidateViews();
	}
   //给当前相关属性赋值
	private void updateLocalData()
	{
		ITDLApplication app = (ITDLApplication) getApplicationContext();
		_top_bar_title.setText(app.getString(CommonDefn.STOCK_DIARY_EDITING_ITEMNAME));
		_itemCode = app.getString(CommonDefn.STOCK_DIARY_EDITING_ITEMCODE);
		String _currentPrice=app.getString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_PRICE);
		if(null!=_currentPrice&&_currentPrice.equals("")){
			_currentPrice="0";
			TDStockLog.d(TAG, "current Price  values is fail");
		}else if(null==_currentPrice){
			_currentPrice="0";
			TDStockLog.d(TAG, "Current  Price  values is null");
		}
		_itemCurrentPrice=_currentPrice;
	}
 //给holder对象更新属性值
	private void updateAdapter()
	{
		
		_list.clear();
		TDStockLog.d(TAG, String.format("userid: %d, itemcode: %s",
				((ITDLApplication) getApplicationContext()).getUserId(-1),
				_itemCode));
		List<String[]> diary = this._dbHelper.getDiaryItemsByItemCode(
						/*this._dbHelper.getUserIdByName(getUser())*/((ITDLApplication) getApplicationContext()).getUserId(-1), _itemCode);
		TDStockLog.d(TAG, String.format("list size: %d", diary == null ? 0 : diary
				.size()));
		int index = 0;
		for (String[] array : diary)
		{
			index++;
			UserDiaryHolder holder = new UserDiaryHolder();
			holder.header = new TextView(this);
			holder.net = new TextView(this);
			holder.desc = new TextView(this);
            

			holder.id = Integer.parseInt(array[0]); //primary key: recno
			holder.itemCode = _itemCode;
			holder.diaryPrice = Double.parseDouble(array[3]);
			holder.lotsize = Integer.parseInt(array[2]);
			holder.date = DateUtils.strToDate(array[1], "yyyy-MM-dd");
			holder.currentPrice = Double.parseDouble(_itemCurrentPrice==null||_itemCurrentPrice.equals("")?"0":_itemCurrentPrice);
			holder.desc.setText(array[4] == null ? "" : array[4]);
			_list.add(holder);
		}

		//_adapter.notifyDataSetChanged();
		//_listView.invalidateViews();
		_newAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		this._dbHelper.cleanup();
		super.onDestroy();
	}

	@Override
	protected void onRestart()
	{
		// TODO Auto-generated method stub
		if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}
		super.onRestart();
	}

	private synchronized void setAdapterToAddAnotherClickableBtn()
	{
		_newAdapter = new UserDiaryItemAdapter(LayoutInflater.from(StockDiaryActivity.this), _list);
		_listView.setAdapter(_newAdapter);
	}

    public	 class NewDiary extends DefaultClickHandler
	{
		NewDiary(Context context)
		{
			super(context);
		}

		@Override
		protected void onDefaultAction()
		{
			ITDLApplication app = (ITDLApplication) getApplicationContext();
			app.putString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO,null);
			Intent intent = new Intent(getApplicationContext(),
					StockDiaryEditActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			SwitchForwardActivity(StockDiaryEditActivity.class, intent);
		}

	}
	

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		//share the same tab with  more group,
		return MonitorGroup.GetActivityGroupHostControl() == null ?  MoreGroup.GetActivityGroupHostControl() : MonitorGroup.GetActivityGroupHostControl() ;
	}
   
	//本方法把SwitchForwardActivity的访问修饰符改成public 
	public  void SwitchForwardActivity(Intent intent){
		SwitchForwardActivity(StockDiaryEditActivity.class, intent);
	}
}
